import * as signalR from '@microsoft/signalr'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

interface User {
    message: string
    list: string[]   // emails 是字符串数组
    , token: string
    , Id: number
    , Name: string
    , Password: string
    , userId: string
    , userMsg: string
}

const Singlrs = function () {
    const msg = reactive<User>({ message: "", list: [], token: "", Id: 0, Name: "", Password: "", userId: "", userMsg: "" })
    let connection: any = null
    const option: signalR.IHttpConnectionOptions = {
        transport: signalR.HttpTransportType.WebSockets, // ✅ 强制使用 WebSockets
        skipNegotiation: true                            // ✅ 跳过协商
        , withCredentials: true // ⚠️ 必须启用，和后端 AllowCredentials 对应
    }
    option.accessTokenFactory = () => {
        return msg.token
    }
    // onMounted(async () => {
    //     // console.log(1)
    //     connection = new signalR.HubConnectionBuilder()
    //         .withUrl('http://localhost:5200/maphub/singlr', {

    //         }) // 修改为你的后端地址
    //         .withAutomaticReconnect()
    //         .build()
    //     await connection.start()
    //         .then(() => console.log("✅ SignalR 已连接"))
    //         .catch((err: any) => console.error("❌ SignalR 连接失败", err))

    //     connection.on('ReceivePublicMessage', (user: string, message: any) => {
    //         msg.list.push(user)
    //         console.log(message)
    //     })
    // })
    //私发消息
    function PrivatehandleEnter() {
        loginEvent()
        if (connection) {
            connection.invoke('SendPriviteMessage', msg.userId, msg.userMsg)
                .catch((err: any) => console.error('❌ send failed:', err))
        }
    }
    function handleEnter() {
        loginEvent()
        if (connection) {
            connection.invoke('SendPublicMessage', msg.message)
                .catch((err: any) => console.error('❌ send failed:', err))
        }
    }
    //登录
    const LoginFunc = async () => {
        try {
            const response = await axios.post('http://localhost:5200/api/Login/Login', {
                Id: msg.Id,
                Password: msg.Password,
                Name: msg.Name
            });
            msg.token = response.data
            console.log('响应数据:', response.data)
            loginEvent()
        } catch (error) {
            console.error('请求失败:', error)
        }
    };

    //推送消息
    const loginEvent = async function () {
        if (connection != null) {
            return
        }
        const option: signalR.IHttpConnectionOptions = {
            transport: signalR.HttpTransportType.WebSockets, // ✅ 强制使用 WebSockets
            skipNegotiation: true                            // ✅ 跳过协商
            , withCredentials: true // ⚠️ 必须启用，和后端 AllowCredentials 对应
        }
        option.accessTokenFactory = () => {
            return msg.token
        }
        // console.log(1)
        connection = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:5200/maphub/singlr', option) // 修改为你的后端地址
            .withAutomaticReconnect()
            .build()
        await connection.start()
            .then(() => console.log("✅ SignalR 已连接"))
            .catch((err: any) => console.error("❌ SignalR 连接失败", err))

        //监听公共消息
        connection.on('ReceivePublicMessage', (user: string, message: any) => {
            msg.list.push(user)
            console.log(message)
        })
        //监听私法消息
        connection.on('ReceivePrivateMessage', (fromUser: string, message: any) => {
            msg.list.push(`私法消息msg:${message},"foruser:"${fromUser}`)
            console.log(message)
        })

        //监听文件是否解析成功
        connection.on('ReceiveProgress', (count: number, maxCount: number) => {
            uploadProgressJIexi.value = Math.round((count / maxCount) * 100);
            console.log(uploadProgressJIexi.value)
        })
    }

    // 状态
    const selectedFile = ref<File | null>(null)
    const uploadProgress = ref(10)
    const uploadProgressJIexi = ref(1)
    // 选择文件
    const handleFileChange = (event: Event) => {
        const target = event.target as HTMLInputElement
        if (target.files && target.files.length > 0) {
            selectedFile.value = target.files[0]
        }
    }

    //上传文件
    const submitUpload = async () => {
        try {
            // if (!selectedFile.value) {
            //     ElMessage.warning('请先选择文件')
            //     return
            // }
            if (!selectedFile.value) return
            console.log(selectedFile.value.name)
            const formData = new FormData();
            formData.append('file', selectedFile.value)

            await axios.post("http://localhost:5200/api/Login/file", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                    Authorization: `Bearer ${msg.token}`,
                },
                onUploadProgress: (progressEvent) => {
                    if (progressEvent.total) {
                        uploadProgress.value = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        )
                        console.log('上传进度:', uploadProgress.value)
                    }
                },
            });
            ElMessage.success('上传成功')
            //上传成功之后，告诉后端服务解析文件
            loginEvent()
            if (connection) {
                connection.invoke('SendProgress', selectedFile.value.name)
                    .catch((err: any) => console.error('❌ send failed:', err))
            }

        } catch (err) {
            ElMessage.error('上传失败')
            console.error(err)
        }
    };

    return { msg, selectedFile, uploadProgress, uploadProgressJIexi, handleFileChange, submitUpload, handleEnter, LoginFunc, PrivatehandleEnter }
}

export default Singlrs

